(function (w) {
    // 新建文章不传id；编辑文章get传参数id到url中
    let arti_title_in = document.querySelector('.arti_title_in');//标题
    let arti_class_in = document.querySelector('.arti_class_in');//分类
    let add_arti_bar_btn = document.querySelector('.add_arti_bar_btn');//发布按钮
    let editor;//md对象 
    // editor.getMarkdown(): 获取textarea内容
    let id;//文章id（若有会在加载时初始化）


    // 获取文章分类列表
    let renderColSelector = function (classId) {
        ajax({
            method: 'GET',
            url: urlRoot + 'article/class',
        }).then((json) => {
            arti_class_in.innerHTML = '';
            json.data.forEach(item => {
                arti_class_in.add(new Option(item.class_name, item.id));
            });
            selectByValue(arti_class_in, classId);
        }, (error) => {
            alert(error);
        });
    }
    // 渲染源内容
    let renderArticleById = function (articleId) {
        ajax({
            method: 'GET',
            url: urlRoot + 'article/getArticle',
            data: {
                id: articleId
            },
        }).then((json) => {
            // 如果没有这篇文章，数据为空怎么办？
            if (json === undefined) {

            }
            arti_title_in.value = json.data[0].title;
            editor = initEditor(json.data[0].content);
            renderColSelector(json.data[0].class_id);
        }, (error) => {
            alert(error);
        });
    }

    // markdown初始化
    let initEditor = function (md) {
        return editormd("editormd", {
            width: "100%",
            height: "100%",
            path: '../editor.md-master/lib/',
            markdown: md,
            codeFold: true,
            saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
            searchReplace: true,
            emoji: true,
            taskList: true,
            tocm: true,         // Using [TOCM]
            tex: true,                   // 开启科学公式TeX语言支持，默认关闭
            flowChart: true,             // 开启流程图支持，默认关闭
            sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "./php/upload.php",
        });
    }

    // 提交按钮监听
    let putArticle = function () {
        let articleTitle = arti_title_in.value;
        let articleClass = arti_class_in.value;
        let articleContent = editor.getMarkdown();
        if (articleTitle === '' || articleContent === '') {
            alert('标题或内容不能为空');
            return;
        }
        if (hasArtiId()) {//编辑文章
            editArticle(id, articleTitle, articleClass, articleContent);
        } else {//新建文章
            addArticle(articleTitle, articleClass, articleContent);
        }
    };
    add_arti_bar_btn.addEventListener('click', putArticle);
    // 新建文章请求
    let addArticle = function (title, colid, content) {
        ajax({
            method: 'POST',
            url: urlRoot + 'article/addArticle',
            data: {
                class_id: colid,
                title: title,
                content: content,
            },
            header: {
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert('新建文章[' + json.data.title + ']成功!');
            w.location.href = util.getCurrRootUrl() + 'manager.html';
        }, (error) => {
            alert(error);
        });
    }
    // 编辑文章请求
    let editArticle = function (artiid, title, colid, content) {
        ajax({
            method: 'PUT',
            url: urlRoot + 'article/updateArticle',
            data: {
                id: artiid,
                class_id: colid,
                title: title,
                content: content,
            },
            header: {
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert('修改文章[' + json.data.title + ']成功!');
            w.location.href = util.getCurrRootUrl() + 'manager.html';
        }, (error) => {
            alert(error);
        });
    }

    // 判断参数是否包含id
    let hasArtiId = function () {
        let urlArr = w.location.href.split('?');
        if (urlArr.length <= 1) {
            return false;
        }
        return true;
    }
    /**
     * 根据url参数返回id
     * @returns url参数中的id，若id非法返回 -1
     */
    let getIdByUrl = function () {// id有误返回 -1
        let urlArr = w.location.href.split('?');
        let id = parseInt(urlArr[1].split('=')[1]);
        if (isNaN(id)) {
            alert('文章id请求有误');
            w.location.href = urlArr[0];
            return -1;
        }
        return id;
    }

    // 进入页面，渲染分类、文章（如有）
    if (hasArtiId()) {
        id = getIdByUrl();//初始化id
        renderArticleById(id);// 这里的id由params获取
    } else {
        editor = initEditor('');
        renderColSelector(-1);
    }
})(window);